<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2017 河源市卓锐科技有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------
// | 开源协议 ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------

namespace app\warehouse\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\warehouse\model\Freight as FreightModel;
use app\warehouse\model\WareHouse as WareHouseModel;
use app\warehouse\model\Carrier as CarrierModel;
use think\Db;
use util\PHPZip;

/**
 * 运费配置管理控制器
 * @package app\warehouse\controller
 */
class Freight extends Admin
{
    /**
     * 运费配置列表
     * @author 陈梦晨 <2391157750@qq.com>
     * @return mixed
     */
    public function index()
    {
       // 查询
        $map = $this->getMap();
        $id=input('id');
        if($id){
            $map['warehouse_list.warehouseid']=$id;
        }
        $pagetitle="运费配置列表";

        // 排序
        $order = $this->getOrder('sort desc, id asc');
        // 数据列表
        $data_list = FreightModel::getAll($map, $order);
        foreach ($data_list as $key => $value) {
            # code...
            $data_list[$key]['address']=getarea($value['provinceid'],$value['cityid'],$value['townid']);
        }
        // 分页数据
        $page = $data_list->render();

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle($pagetitle) // 设置页面标题
            // ->hideCheckbox()
            ->setTableName('warehouse_freight')
            ->setSearch(['warehousename'=>'仓库名称','carriername'=>'承运商','distributename'=>'配送方式','ProvinceName' => '省份名称','CityName'=>'城市名称','TownName'=>'地区名称']) // 设置搜索框
            ->addFilter('warehouse_list.warehousename,admin_carrier.carriername') // 添加筛选
            ->setPrimaryKey("id")
            ->addTopButton('add') // 添加顶部按钮
            ->addTopButton('enable') // 添加顶部按钮
            ->addTopButton('disable') // 添加顶部按钮
            ->addColumns([ // 批量添加数据列
                ['id', '编号'],
                ['warehousename', '仓库名称'],
                ['address', '区域'],
                ['carriername','承运商'],
                ['distributename','配送方式'],
                ['ykg','首重','text.edit'],
                ['ykgfee','首重资费','text.edit'],
                ['continued','续重','text.edit'],
                ['continuedfee','续重资费','text.edit'],
                ['aging','时效','text.edit'],
                ['sort', '排序', 'text.edit'],
                ['status', '状态', 'switch'],
                ['right_button', '操作', 'btn']
            ])
            ->addOrder(['sort', 'id'])
            ->addRightButton('edit', ['class'=>'btn btn-xs btn-default','icon' => 'fa fa-pencil', 'title' => '编辑', 'href' => url('edit', ['id' => '__id__'])])
            ->addRightButton('delete',['class'=>'btn btn-xs btn-default','icon' => 'fa fa-times', 'title' => '删除', 'href' => url('delete', ['id' => '__id__'])])
            ->addTopButton('import', ['title' => '导入', 'icon' => 'fa fa-fw fa-pencil-square-o', 'href'=> url('freightimport'), 'class' => 'btn btn-danger'], true)
            ->addTopButton('custom', ['title' => '导出', 'icon' => 'fa fa-fw fa-download', 'href'=> url('freightexport'), 'class' => 'btn btn-info js-get'])
            ->addTopButton('custom', ['title' => '下载导入模板', 'icon' => 'fa fa-fw fa-download', 'href'=> url('downloadtpl'), 'class' => 'btn btn-info'])
            ->setRowList($data_list) // 设置表格数据
            ->setPages($page) // 设置分页数据
            ->fetch(); // 渲染模板
    }

    /**
     * 编辑运费配置
     * @param null $id 运费配置id
     * @author 陈梦晨 <2391157750@qq.com>
     */
    public function edit($id = null)
    {
        if ($id === null) return $this->error('缺少参数');
        $info = FreightModel::find(['id' => $id]);
        $list_province = db("admin_area")->where("pid=0")->column("id,name");
        $list_city = db("admin_area")->where("pid=".$info['provinceid'])->column("id,name");
        $list_town = db("admin_area")->where("pid=".$info['cityid'])->column("id,name");

        $list_distribute = db("admin_distribute")->where("carrierid=" . $info['carrierid'])->column("id,title");
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('编辑') // 设置页面标题
            ->setUrl(url('dosave'))
            ->addFormItems([ // 批量添加表单项
                ['hidden', 'id'],
                ['select', 'warehouseid', '仓库', '<span class="text-danger">必选</span>', WareHouseModel::getAllList(['status'=>1,'isdel'=>0],['sort'=>'desc','warehouseid'=>'asc'])],
                ['linkage', 'carrierid', '承运商', '<span class="text-danger">必选</span>', CarrierModel::getAllList(['status'=>1,'isdel'=>0],['sort'=>'desc','carrierid'=>'asc']), '', url('get_distribute'), 'distributeid'],
                ['select', 'distributeid', '配送方式', '<span class="text-danger">必选</span>',$list_distribute],
                ['linkage', 'provinceid','选择省份','<span class="text-danger">必选</span>',$list_province,'', url('get_city'), 'cityid,townid'],
                ['linkage', 'cityid','选择城市','<span class="text-danger">必选</span>',$list_city, '',url('get_area'), 'townid'],
                ['select', 'townid','选择地区','<span class="text-danger">必选</span>',$list_town],
                ['text', 'ykg', '首重（g）', '<span class="text-danger">必填</span>'],
                ['text', 'ykgfee', '首重资费（元）', '<span class="text-danger">必填</span>'],
                ['text', 'continued', '续重（g）', '<span class="text-danger">必填</span>'],
                ['text', 'continuedfee', '续重资费（元）', '<span class="text-danger">必填</span>'],
                ['text', 'aging', '时效（天）', '<span class="text-danger">必填</span>'],
                ['radio', 'status', '状态', '', ['禁用', '启用'],1],
                ['text', 'sort', '排序'],
            ])
            ->layout(['warehouseid'=>4,'carrierid'=>4,'distributeid'=>4,'provinceid'=> 4,'cityid'=>4,'townid'=>4,'ykg'=>4,'ykgfee'=>4,'continued'=>4,'continuedfee'=>4,'aging'=>4,'sort'=>3])
            ->setFormData($info) // 设置表单数据
            ->fetch();
            
    }
    public function dosave(){
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();
            
            // 验证
            $result = $this->validate($data, 'Freight');
            // 验证失败 输出错误信息
            if(true !== $result) return $this->error($result);

            if ($menu = FreightModel::update($data)) {
                return $this->success('修改成功', url('index'));
            } else {
                return $this->error('修改失败');
            }
        }
    }
    /**
     * 新增运费配置
     * @author 陈梦晨 <2391157750@qq.com>
     */

    public function add(){
        $list_province = db("admin_area")->where("pid=0")->column("id,name");
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('新增') // 设置页面标题
            ->setUrl(url('doadd'))
            ->addFormItems([ // 批量添加表单项
                ['select', 'warehouseid', '仓库', '<span class="text-danger">必选</span>', WareHouseModel::getAllList(['status'=>1,'isdel'=>0],['sort'=>'desc','warehouseid'=>'asc'])],
                ['linkage', 'carrierid', '承运商', '<span class="text-danger">必选</span>', CarrierModel::getAllList(['status'=>1,'isdel'=>0],['sort'=>'desc','carrierid'=>'asc']), '', url('get_distribute'), 'distributeid'],
                ['select', 'distributeid', '配送方式', '<span class="text-danger">必选</span>'],
                ['linkage', 'provinceid','选择省份','<span class="text-danger">必选</span>',$list_province,'', url('get_city'), 'cityid,townid'],
                ['linkage', 'cityid','选择城市','<span class="text-danger">必选</span>','', '',url('get_area'), 'townid'],
                ['select', 'townid','选择地区','<span class="text-danger">必选</span>',],
                ['text', 'ykg', '首重（g）', '<span class="text-danger">必填</span>'],
                ['text', 'ykgfee', '首重资费（元）', '<span class="text-danger">必填</span>'],
                ['text', 'continued', '续重（g）', '<span class="text-danger">必填</span>'],
                ['text', 'continuedfee', '续重资费（元）', '<span class="text-danger">必填</span>'],
                ['text', 'aging', '时效（天）', '<span class="text-danger">必填</span>','1'],
                ['radio', 'status', '状态', '', ['禁用', '启用'],1],
                ['text', 'sort', '排序'],
            ])
            ->layout(['warehouseid'=>4,'carrierid'=>4,'distributeid'=>4,'provinceid'=> 4,'cityid'=>4,'townid'=>4,'ykg'=>4,'ykgfee'=>4,'continued'=>4,'continuedfee'=>4,'aging'=>4,'sort'=>3])
            ->fetch();
    }
    public function doadd(){
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();
            // 验证
            $result = $this->validate($data, 'Freight');
            // 验证失败 输出错误信息
            if(true !== $result) return $this->error($result);

            if ($menu = FreightModel::create($data)) {
                return $this->success('新增成功', url('index'));
            } else {
                return $this->error('新增失败');
            }
        }
    }
    public function freightimport(){
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if(empty($data['excelfile'])){
                $this->error('请上传文件');
            }
            $file = Db::name('admin_attachment')->where('id', $data['excelfile'])->value('path');
            $filetmpname = $_SERVER['DOCUMENT_ROOT'] . '/public/' . $file;

            import('util.PHPExcel', EXTEND_PATH, '.class.php');
            $PHPExcel = new \PHPExcel(); 
            $PHPReader = new \PHPExcel_Reader_Excel2007(); 
            if(!$PHPReader->canRead($filetmpname)){ 
                $PHPReader = new \PHPExcel_Reader_Excel5(); 
                if(!$PHPReader->canRead($filetmpname)){ 
                    $PHPReader = new \PHPExcel_Reader_CSV();
                    if(!$PHPReader->canRead($filetmpname)){
                        $this->error('文档解析错误');
                    }
                } 
            } 
            $PHPExcel = $PHPReader->load($filetmpname); 
            $freight=array();
            $sheet = $PHPExcel->getSheet(0);
            $highestRow = $sheet->getHighestRow();
            $strOut="";
            for ($row = 2; $row <= $highestRow; $row++){
                $warehousename=$sheet->getCell('A'.$row)->getValue();
                if(empty($warehousename)){
                    continue;
                }
                $warehouse=db('warehouse_list')->where(array('warehousename'=>$sheet->getCell('A'.$row)->getValue()))->find();
                if(!$warehouse){
                    $strOut.="第:{$row}行信息导入失败：错误信息是仓库信息不存在\r\n";
                    continue;
                }
                $carrier=db('admin_carrier')->where(array('carriername'=>$sheet->getCell('B'.$row)->getValue()))->find();
                if(!$carrier){
                    $strOut.="第:{$row}行信息导入失败：错误信息是承运商信息不存在\r\n";
                    continue;
                }
                $province=db('admin_area')->where(array('name'=>$sheet->getCell('C'.$row)->getValue()))->find();
                if(!$province){
                    $strOut.="第:{$row}行信息导入失败：错误信息是省/市信息不存在\r\n";
                    continue;
                }
                $city=db('admin_area')->where(array('name'=>$sheet->getCell('D'.$row)->getValue()))->find();
                if(!$city){
                    $strOut.="第:{$row}行信息导入失败：错误信息是市/区信息不存在\r\n";
                    continue;
                }
                $town=db('admin_area')->where(array('name'=>$sheet->getCell('E'.$row)->getValue()))->find();
                if(!$town){
                    $strOut.="第:{$row}行信息导入失败：错误信息是区/县信息不存在\r\n";
                    continue;
                }
                $warehouse_freight=db('warehouse_freight')
                        ->where(array(
                            'warehouseid'=>$warehouse['warehouseid'],
                            'carrierid'=>$carrier['carrierid'],
                            'provinceid'=>$province['id'],
                            'cityid'=>$city['id'],
                            'townid'=>$town['id']
                        ))
                        ->find();
                if(!$warehouse_freight){
                    $freight=array(
                        'warehouseid'=>$warehouse['warehouseid'],
                        'carrierid'=>$carrier['carrierid'],
                        'provinceid'=>$province['id'],
                        'cityid'=>$city['id'],
                        'townid'=>$town['id'],
                        'ykg'=>$sheet->getCell('F'.$row)->getValue(),
                        'ykgfee'=>$sheet->getCell('G'.$row)->getValue(),
                        'continued'=>$sheet->getCell('H'.$row)->getValue(),
                        'continuedfee'=>$sheet->getCell('I'.$row)->getValue(),
                        'aging'=>$sheet->getCell('J'.$row)->getValue(),
                        'status'=>$sheet->getCell('K'.$row)->getValue(),
                        'sort'=>$sheet->getCell('L'.$row)->getValue(),
                        );
                    $aid=db("warehouse_freight")->insert($freight);
                }else{
                    $freight=array(
                        'ykg'=>$sheet->getCell('F'.$row)->getValue(),
                        'ykgfee'=>$sheet->getCell('G'.$row)->getValue(),
                        'continued'=>$sheet->getCell('H'.$row)->getValue(),
                        'continuedfee'=>$sheet->getCell('I'.$row)->getValue(),
                        'aging'=>$sheet->getCell('J'.$row)->getValue(),
                        'status'=>$sheet->getCell('K'.$row)->getValue(),
                        'sort'=>$sheet->getCell('L'.$row)->getValue(),
                        );
                    $freight['id']=$warehouse_freight['id'];
                    $aid=db("warehouse_freight")->update($freight);
                }
                if (!$aid) {
                    $errormsg=D("user")->getError();
                    $strOut.="第:{$row}行信息导入失败：错误信息是{$errormsg}\r\n";
                }
            }
            
            if($strOut!=""){
                $this->error($strOut);
            }else{
                $this->success('导入成功', null, ['_close_pop' => 1,'_parent_reload'=>1]);
            }

        }

        return ZBuilder::make('form')
            ->addFormItems([ // 批量添加列            
                ['importfile', 'excelfile'],
            ])
            ->fetch();
    }

    public function freightexport(){
        $data = $this->request->get();
        $where['a.id'] = array('in',$data['ids']);

        $count =  db('warehouse_freight a')
                ->join('warehouse_list b', 'a.warehouseid=b.warehouseid', 'left')
                ->join('admin_carrier c', 'a.carrierid=c.carrierid', 'left')
                ->where($where)
                ->count();
                
        $filename=date("Ymd-His");
        $i=0;
        $j=1;
        do{
            $outputdata = db('warehouse_freight a')
                ->join('warehouse_list b', 'a.warehouseid=b.warehouseid', 'left')
                ->join('admin_carrier c', 'a.carrierid=c.carrierid', 'left')
                ->join('admin_area d', 'a.provinceid=d.id', 'left')
                ->join('admin_area e', 'a.cityid=e.id', 'left')
                ->join('admin_area f', 'a.townid=f.id', 'left')
                ->where($where)
                ->page($j,1000)
                ->order(array("a.id" => "desc"))
                ->field("a.id,b.warehousename,c.carriername,d.name as provincename,e.name as cityname,f.name as townname,a.ykg,a.ykgfee,a.continued,a.continuedfee,a.aging,a.status,a.sort")
                ->select();
            foreach ($outputdata as $key => $value) {
                # code...
                $outputdata[$key]['status']=($value['status']==1) ? '启用' : '禁用' ;
            }
            //设置要导出excel的表头
            $title = array('编号','仓库','承运商','省/市','市/区','区/县','首重','首重资费','续重','续重资费','时效','状态','排序');
            //进行导出
            $this->excelexport($outputdata, date("Ymd-His")."-".$j,$title,$filename);

            unset($outputdata);
            //ob_flush();//修改部分
            //flush();
            $j++;
            $i+=1000;
        }while($i<=$count);
        
        $dbpath = "./public/uploads/exportzip/";
        $zippath = $dbpath;

        $bakup=$filename;
        //zip文件名
        $z=new \util\PHPZip(); //新建立一个zip的类
        $z->ZipAndDownload($dbpath."/".$bakup,$bakup); //添加指定目录
    }
    //导出Excel表格
    protected function excelexport($data,$excelFileName,$sheetTitle,$filename){
        import('util.PHPExcel', EXTEND_PATH, '.class.php');
        /* 实例化类 */
        $objPHPExcel = new \PHPExcel(); 
        
        /* 设置输出的excel文件为2007兼容格式 */
        $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
        
        /* 设置当前的sheet */
        $objPHPExcel->setActiveSheetIndex(0);
        
        $objActSheet = $objPHPExcel->getActiveSheet();
        $k = 'A';
        foreach($sheetTitle as $vo)
        { 
            $objActSheet->setCellValue($k.'1',$vo);
            $k++;
        }
        
        $i = 2;
        foreach($data as $value)
        {   
            /* excel文件内容 */
            $j = 'A';
            foreach($value as $value2)
            { 
                //            $value2=iconv("gbk","utf-8",$value2);
                $objActSheet->setCellValue($j.$i,' '.$value2);
                $j++;
            }
            $i++;
        }
        if(!file_exists($_SERVER['DOCUMENT_ROOT'] . "/public/uploads/exportzip/".$filename."/")){
            mkdir($_SERVER['DOCUMENT_ROOT'] . "/public/uploads/exportzip/".$filename."/",0777);
            chmod($_SERVER['DOCUMENT_ROOT'] . "/public/uploads/exportzip/".$filename."/",0777);
        } 
        $objWriter->save($_SERVER['DOCUMENT_ROOT']."/public/uploads/exportzip/".$filename."/" . $excelFileName.'.xlsx');
        //ob_end_clean();  //清空缓存
        ///* 生成到浏览器，提供下载 */ 
        //ob_end_clean();  //清空缓存             
        //header("Pragma: public");
        //header("Expires: 0");
        //header("Cache-Control:must-revalidate,post-check=0,pre-check=0");
        ////header("Content-Type:application/force-download");
        //header("Content-Type:application/vnd.ms-execl");
        //header("Content-Type:application/octet-stream");
        ////header("Content-Type:application/download");
        //header('Content-Disposition:attachment;filename="'.$excelFileName.'.xls"');
        //header("Content-Transfer-Encoding:binary"); 
        //$objWriter->save('php://output');
    }
    //下载模板
    public function downloadtpl() {
        $file=$_SERVER['DOCUMENT_ROOT']. "/public/uploads/template/warehouse_freight.xlsx";
        if(is_file($file)) {
            header("Content-Type: application/force-download");
            header("Content-Disposition: attachment; filename=".basename($file));
            readfile($file);
            exit;
        }else{
            $this->error('文件不存在！');
        }
    }
    /**
     * 删除运费配置
     * @author 陈梦晨 <2391157750@qq.com>
     * @return mixed
     */
    public function delete($record = [])
    {
        $id = $this->request->param('id');
        // 删除节点
        if (FreightModel::destory($id)) {
            return $this->success('删除成功');
        } else {
            return $this->error('删除失败');
        }
    }

    /**
     * 设置状态
     * @param string $type 状态类型:enable/disable
     * @param array $record 行为日志内容
     * @author 陈梦晨 <2391157750@qq.com>
     * @return mixed
     */
    public function setstatus($type = '', $record = [])
    {
        $ids = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        if (empty($ids)) return $this->error('缺少主键');

        if(FreightModel::$type($ids)){
            return $this->success('操作成功');
        }else{
            return $this->error('操作失败');
        }
            
    }

    /**
     * 禁用
     * @param array $record 行为日志内容
     * @author 陈梦晨 <2391157750@qq.com>
     * @return mixed
     */
    public function disable($record = [])
    {
        return $this->setstatus('disable');
    }

    /**
     * 启用
     * @param array $record 行为日志内容
     * @author 陈梦晨 <2391157750@qq.com>
     * @return mixed
     */
    public function enable($record = [])
    {
        return $this->setstatus('enable');
    }

    public function get_city($provinceid = '') {
        $result = db("admin_area")->where("pid=" . $provinceid)->field("id,name")->select();
        $list=[];
        foreach ($result as $key => $value) {
            # code...
            $list[$key]['key']=$value['id'];
            $list[$key]['value']=$value['name'];
        }
        
        $arr['code'] = '1'; //判断状态
        $arr['msg'] = '请求成功'; //回传信息
        $arr['list'] = $list; //数据
        return json($arr);
    }

    public function get_area($cityid = '') {
        $result = db("admin_area")->where("pid=" . $cityid)->field("id,name")->select();
        $list=[];
        foreach ($result as $key => $value) {
            # code...
            $list[$key]['key']=$value['id'];
            $list[$key]['value']=$value['name'];
        }
        
        $arr['code'] = '1'; //判断状态
        $arr['msg'] = '请求成功'; //回传信息
        $arr['list'] = $list; //数据
        return json($arr);
    }

    public function get_distribute($carrierid = ''){
        $result = db("admin_distribute")->where("carrierid=" . $carrierid)->field("id,title")->select();
        $list=[];
        foreach ($result as $key => $value) {
            # code...
            $list[$key]['key']=$value['id'];
            $list[$key]['value']=$value['title'];
        }
        
        $arr['code'] = '1'; //判断状态
        $arr['msg'] = '请求成功'; //回传信息
        $arr['list'] = $list; //数据
        return json($arr);
    }
}